package spring.demo.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@RestController
@RequestMapping("/file")
public class FileController {

    @RequestMapping("/")
    public void downloadResource(@RequestParam(value = "fileName", required = true) String fileName, HttpServletResponse response) {
        String dataDirectory = "D:\\code\\libs_demo";
        fileName = "pom.xml";
        Path file = Paths.get(dataDirectory, fileName);
        if (Files.exists(file)) {
            response.setContentType("application/x-gzip");
            try {
                response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
                Files.copy(file, response.getOutputStream());
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}
